﻿using XinLife.Common.Filters;
using XinLife.Core.Model;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace XinLife.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [WriteLog]
    [Common.Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "," + JwtBearerDefaults.AuthenticationScheme + ",UserAuthent")]
    public class BaseController : ControllerBase
    {

        /// <summary>
        /// 返回成功
        /// </summary>
        /// <param name="data">返回的数据</param>
        /// <returns></returns>
        [NonAction]
        public AjaxResult Success(object data = null)
        {
            AjaxResult res = new AjaxResult
            {
                code = 200,
                msg = "请求成功！",
                data = data
            };
            return res;
        }

        /// <summary>
        /// 返回成功
        /// </summary>
        /// <param name="msg">返回的消息</param>
        /// <param name="data">返回的数据</param>
        /// <returns></returns>
        [NonAction]
        public AjaxResult Success(string msg, object data)
        {
            AjaxResult res = new AjaxResult
            {
                code = 200,
                msg = msg,
                data = data
            };
            return res;
        }

        /// <summary>
        /// 返回错误
        /// </summary>
        /// <param name="msg">错误提示</param>
        /// <returns></returns>
        [NonAction]
        public AjaxResult Error(string msg)
        {
            AjaxResult res = new AjaxResult
            {
                code = 0,
                msg = msg,
                data = null
            };
            return res;
        }

        [NonAction]
        public AjaxResult Error(ModelStateDictionary ModelState)
        {
            List<string> erroMsg = new List<string>();
            List<string> Keys = ModelState.Keys.ToList();
            //获取每一个key对应的ModelStateDictionary
            foreach (var key in Keys)
            {
                var errors = ModelState[key].Errors.ToList();
                //将错误描述添加到sb中 
                foreach (var error in errors)
                {
                    erroMsg.Add(error.ErrorMessage);
                }
            }
            return new AjaxResult
            {
                code = 400,
                msg = "数据验证错误",
                data = erroMsg
            };
        }

    }
}